/*
Copyright (c) 2011, Stephane Albert
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the organization nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHANE ALBERT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "debridFetcherRD.h"

debridFetcherRD::debridFetcherRD() {
}

debridFetcherRD::~debridFetcherRD() {
    stop();
    logout();
}

//TODO implement new version of login with md5 and timestamp
bool debridFetcherRD::authClient(const std::string& username, const std::string& password) {
    if (curlHandle != NULL) {
        std::string URL = "http://www.real-debrid.com/ajax/login.php?user="+username+"&pass="+password;
        std::string retPage = getData(URL);
        if (retPage.length() == 0)
            return false;
        size_t isFound = retPage.find("OK");
        if (isFound != std::string::npos)
            return true;
    }
    return false;
}

std::string debridFetcherRD::debridLink(const std::string &linkURL) {
    if (curlHandle == NULL)
        return _("CURL not init.");
    logMessage(linkURL, DEBRID);
    //Post AJAX Like
    std::string ajaxLinkURL = "http://www.real-debrid.com/ajax/unrestrict.php?link=";
    ajaxLinkURL.append(linkURL);
    ajaxLinkURL.append("&password=&remote=0");
    std::string retPage = getData(ajaxLinkURL);
    if (retPage.length() == 0)
        return _("Unable to fetch AJAX request.");
    //Error handling
    //Parse JSON response
    size_t begPos = retPage.find("error");
    if (begPos != std::string::npos) {
        begPos += 7;
        if (retPage.at(begPos) != '0') {    //We've got an error !
            ++begPos;
            size_t endPos = retPage.find('"', begPos);
            std::string errorMsg = retPage.substr(begPos, endPos-begPos);
            return errorMsg;
        }
    }
    begPos = retPage.find("generated_links");
    if (begPos != std::string::npos) {
        begPos += 16;
        begPos = retPage.find("|-|", begPos);
        if (begPos != std::string::npos) {    //We've got a link
            begPos += 3;
            size_t endPos = retPage.find('"', begPos);
            std::string debLink = retPage.substr(begPos, endPos-begPos);
            size_t escFound = 0;
            while ((escFound = debLink.find('\\', escFound)) != std::string::npos)
                debLink.erase(escFound, 1);
            return debLink;
        }
    }
    return _("Unknown Error");
}

void debridFetcherRD::logout() {
    if (curlHandle == NULL)
        return;
    getData("http://www.real-debrid.com/logout");
}

bool debridFetcherRD::isDebrid(const std::string& link) {
    if (link.find("real-debrid.") != std::string::npos)
        return true;
    return false;
}

bool debridFetcherRD::checkFileForError(const std::string& filePath) {      //TODO Need DOX
    //Error during debrid is issued with a 404 error.
    std::ifstream inFile;
    inFile.open(filePath.c_str(), std::ios_base::binary);
    if (!inFile.good())
        return true;
    inFile.seekg(0, std::ios_base::end);
    std::streampos filesize = inFile.tellg();
    if (filesize < 5120) {		//If size < 5Kb might be an error message (error as html)
        char rawInput[5120];
        inFile.seekg(0, std::ios_base::beg);
        inFile.read(rawInput, 5119);
        rawInput[inFile.gcount()] = '\0';
        std::string inputStr = rawInput;        //Don't want to use legacy cstr
        if (inputStr.length() != filesize)      //We've hit a NULL term, file is not text
            return false;
        std::string errorMsg = "<title>An error occured while processing your request";
        if (inputStr.find(errorMsg) != std::string::npos) {
            return true;
        }
        errorMsg = "<title>404 Not Found";
        if (inputStr.find(errorMsg) != std::string::npos) {
            return true;
        }
        errorMsg = "type: \"error\"";
        if (inputStr.find(errorMsg) != std::string::npos) {
            return true;
        }
        errorMsg = "Your code is not or no longer valid";
        if (inputStr.find(errorMsg) != std::string::npos) {
            return true;
        }
        errorMsg = "Your download code does not exist in our database";
        if (inputStr.find(errorMsg) != std::string::npos) {
            return true;
        }
        errorMsg = "A Premium account for the hoster is missing or inactive";
        if (inputStr.find(errorMsg) != std::string::npos) {
            return true;
        }
        errorMsg = "The traffic of the Premium account for the hoster is exceeded";
        if (inputStr.find(errorMsg) != std::string::npos) {
            return true;
        }
    }
    return false;
}
